package com.kuangjia.student_ems.controller;

import com.kuangjia.student_ems.dto.UserDTO;
import com.kuangjia.student_ems.dto.request.UserUpdateRequest;
import com.kuangjia.student_ems.dto.request.ChangePasswordRequest;
import com.kuangjia.student_ems.dto.request.EmailVerificationRequest;
import com.kuangjia.student_ems.entity.User;
import com.kuangjia.student_ems.service.UserService;
import com.kuangjia.student_ems.service.SalaryService;
import com.kuangjia.student_ems.service.EmailCodeService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private SalaryService salaryService;

    @Autowired
    private EmailCodeService emailCodeService;

    @GetMapping
    @PreAuthorize("hasAnyRole('HR_ADMIN', 'DEPARTMENT_MANAGER')")
    public ResponseEntity<List<UserDTO>> getAllUsers() {
        try {
            return ResponseEntity.ok(userService.getAllUsers());
        } catch (Exception e) {
            logger.error("获取所有用户时发生异常", e);
            throw e;
        }
    }

    @GetMapping("/search")
    @PreAuthorize("hasAnyRole('HR_ADMIN', 'DEPARTMENT_MANAGER')")
    public ResponseEntity<List<UserDTO>> searchUsers(@RequestParam String keyword) {
        try {
            return ResponseEntity.ok(userService.searchUsers(keyword));
        } catch (Exception e) {
            logger.error("搜索用户时发生异常，关键词: {}", keyword, e);
            throw e;
        }
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('HR_ADMIN', 'DEPARTMENT_MANAGER') or #id == authentication.principal.getId()")
    public ResponseEntity<UserDTO> getUserById(@PathVariable Long id) {
        try {
            return ResponseEntity.ok(userService.getUserById(id));
        } catch (Exception e) {
            logger.error("根据ID获取用户时发生异常，用户ID: {}", id, e);
            throw e;
        }
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('HR_ADMIN') or #id == authentication.principal.getId()")
    public ResponseEntity<UserDTO> updateUser(@PathVariable Long id, @Valid @RequestBody UserUpdateRequest userUpdateRequest) {
        try {
            return ResponseEntity.ok(userService.updateUser(id, userUpdateRequest));
        } catch (Exception e) {
            logger.error("更新用户时发生异常，用户ID: {}", id, e);
            throw e;
        }
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('HR_ADMIN')")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        try {
            userService.deleteUser(id);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
            logger.error("删除用户时发生异常，用户ID: {}", id, e);
            throw e;
        }
    }

    @GetMapping("/department/{departmentId}")
    @PreAuthorize("hasAnyRole('HR_ADMIN', 'DEPARTMENT_MANAGER')")
    public ResponseEntity<List<UserDTO>> getUsersByDepartment(@PathVariable Long departmentId) {
        try {
            return ResponseEntity.ok(userService.getUsersByDepartment(departmentId));
        } catch (Exception e) {
            logger.error("根据部门获取用户时发生异常，部门ID: {}", departmentId, e);
            throw e;
        }
    }

    @GetMapping("/role/{role}")
    @PreAuthorize("hasRole('HR_ADMIN')")
    public ResponseEntity<List<UserDTO>> getUsersByRole(@PathVariable User.UserRole role) {
        try {
            return ResponseEntity.ok(userService.getUsersByRole(role));
        } catch (Exception e) {
            logger.error("根据角色获取用户时发生异常，角色: {}", role, e);
            throw e;
        }
    }

    /**
     * 分页查询用户
     */
    @GetMapping("/page")
    @PreAuthorize("hasAnyRole('HR_ADMIN', 'DEPARTMENT_MANAGER')")
    public IPage<UserDTO> getUserPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String keyword) {
        try {
            if (pageNum < 1) pageNum = 1;
            if (pageSize < 1) pageSize = 10;
            Page<User> page = new Page<>(pageNum, pageSize);
            return userService.getUserPage(page, keyword);
        } catch (Exception e) {
            logger.error("分页查询用户时发生异常，页码: {}, 页大小: {}, 关键词: {}", pageNum, pageSize, keyword, e);
            // 返回空分页对象，前端能收到明确提示
            Page<UserDTO> emptyPage = new Page<>();
            emptyPage.setRecords(java.util.Collections.emptyList());
            emptyPage.setTotal(0);
            return emptyPage;
        }
    }

    /**
     * 员工薪资发放模块：员工可见，可变更自己薪资状态
     */
    @PutMapping("/{id}/payroll/status")
    @PreAuthorize("hasRole('EMPLOYEE') and #id == authentication.principal.id")
    public ResponseEntity<?> updatePayrollStatus(@PathVariable Long id, @RequestParam Long salaryRecordId, @RequestParam String status) {
        // 这里只允许员工本人操作自己的薪资发放状态
        // status参数如：CONFIRMED、PAID
        // 具体实现可调用SalaryService
        try {
            // 这里假设SalaryService有updateSalaryStatus方法
            boolean result = salaryService.updateSalaryStatus(salaryRecordId, status, id);
            if (result) {
                return ResponseEntity.ok().build();
            } else {
                return ResponseEntity.status(403).body("无权操作或状态无效");
            }
        } catch (Exception e) {
            logger.error("员工变更薪资状态异常", e);
            return ResponseEntity.status(500).body("操作失败: " + e.getMessage());
        }
    }

    /**
     * 修改密码接口，用户需提供原密码、新密码和邮箱验证码
     */
    @PostMapping("/{id}/change-password")
    @PreAuthorize("#id == authentication.principal.getId()")
    public ResponseEntity<?> changePassword(@PathVariable Long id, @Valid @RequestBody ChangePasswordRequest request) {
        try {
            boolean result = userService.changePassword(id, request.getOldPassword(), request.getNewPassword(), request.getEmail(), request.getEmailCode());
            if (result) {
                return ResponseEntity.ok().body("密码修改成功");
            } else {
                return ResponseEntity.status(400).body("原密码错误或验证码无效");
            }
        } catch (Exception e) {
            logger.error("修改密码异常", e);
            return ResponseEntity.status(500).body("操作失败: " + e.getMessage());
        }
    }

    /**
     * 发送修改密码验证码
     */
    @PostMapping("/{id}/send-password-verification")
    @PreAuthorize("#id == authentication.principal.getId()")
    public ResponseEntity<?> sendPasswordVerification(@PathVariable Long id, @RequestBody EmailVerificationRequest request) {
        try {
            // 验证邮箱是否属于当前用户
            UserDTO currentUser = userService.getUserById(id);
            if (!request.getEmail().equals(currentUser.getEmail())) {
                return ResponseEntity.badRequest().body("邮箱地址与当前用户不匹配");
            }
            
            boolean success = emailCodeService.sendEmailCode(request.getEmail());
            if (success) {
                return ResponseEntity.ok().body("验证码发送成功");
            } else {
                return ResponseEntity.badRequest().body("验证码发送失败，请稍后重试");
            }
        } catch (Exception e) {
            logger.error("发送修改密码验证码异常", e);
            return ResponseEntity.status(500).body("发送失败: " + e.getMessage());
        }
    }
} 